package cn.edu.pzhu.dao.imp;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import cn.edu.pzhu.dao.UserDAO;
import cn.edu.pzhu.pojo.User;
import cn.edu.pzhu.util.DruidUtil;

public class UserDAOImp implements UserDAO {
	
	private JdbcTemplate template = new JdbcTemplate(DruidUtil.getDataSource());

	@Override
	public int insert(User t) {
		String sql = "insert into user values(?,?,?)";
		try {
			return template.update(sql, t.getUsername(),t.getPassword(),t.getStatus());
		} catch (Exception e) {
			return -1;
		}
	}

	@Override
	public int update(String key, User t) {
		String sql = "update user set password=?,status=? where username=?";
		try {
			return template.update(sql, t.getPassword(),t.getStatus(),key);
		} catch (Exception e) {
			return -1;
		}
	}
	
	@Test
	public void test() {
		String key = "1";
		User user = new User("1", "123456", 1);
		System.out.println(update(key, user));
	}

	@Override
	public User selectById(String key) {
		String sql="select * from user where username=?";
		try {
			return template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class),key);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List<User> selectAll() {
		List<User> list = null;
		String sql = "select * from user";
		try {
			list = template.query(sql, new BeanPropertyRowMapper<>(User.class));
		} catch (Exception e) {
			//没有查到任何用户，会抛出异常
		}		
		return list;
	}

	@Override
	public int destroy(String username) {
		String sql = "update user set status=? where username=?";
		try {
			return template.update(sql,0,username);
		} catch (Exception e) {
			return -1;
		}	
	}

}
